<template>
  <div>
    <div class="app-content-illustrate">
      <div class="video-background">
        <video autoplay muted loop class="background-video" @error="handleVideoError" @loadedmetadata="handleVideoLoad" playsinline>
          <source src="/video_20018045927eca_mark.mp4" type="video/mp4">
          您的浏览器不支持视频标签。
        </video>
        <!-- 备用背景图片 -->
        <div class="fallback-background"></div>
      </div>
      <div class="content-overlay">
        <p>叶境 · "一叶一世界，一屏一风景"</p>
        <p>免费高清壁纸下载平台，不设任何限制！</p>
        <P>提供4K、8K超清壁纸，涵盖风景、动物、动漫、游戏等多个壁纸分类</P>
      </div>
    </div>
    <div class="app-content-dynamic-images">
      <h3 class="section-title">
        精选壁纸
      </h3>
      
      <!-- 加载状态 -->
      <div v-if="loading" class="loading">
        <div class="loading-spinner"></div>
        <p>加载中...</p>
      </div>
      
      <!-- 精选壁纸列表 -->
      <div v-else class="image-grid">
        <div 
          v-for="(image, index) in selectedWallpapers" 
          :key="index"
          class="image-card"
          v-show="!failedImages.has(image.id)"
        >
          <div class="image-wrapper">
            <!-- 图片格式 -->
            <img 
              v-if="!isVideo(image.url)"
              :src="image.url" 
              :alt="image.name" 
              class="grid-image"
              @error="handleImageError(image.id)"
            />
            <!-- 视频格式 -->
            <video 
              v-else
              :src="image.url"
              class="grid-video"
              muted
              loop
              autoplay
              preload="metadata"
              @error="handleImageError(image.id)"
              @loadedmetadata="handleVideoLoad"
            ></video>
            <!-- 移除视频标识 -->
            <div class="image-overlay">
              <div class="overlay-content">
                <h4>{{ image.name }}</h4>
                <p>{{ image.classify || '精选壁纸' }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!--热门标签-->
    <div class="app-content-Hot-Tags">
      <div class="hot-tags-header">
        <h3 class="section-title">
          热门标签
        </h3>
      </div>
      <div class="app-content-Hot-Tags-box">
        <div class="tags-grid">
          <span class="tag-item" @click="handleTagClick('海洋')">
            海洋
          </span>
          <span class="tag-item" @click="handleTagClick('山脉')">
            山脉
          </span>
          <span class="tag-item" @click="handleTagClick('沙漠')">
            沙漠
          </span>
          <span class="tag-item" @click="handleTagClick('动漫')">
            动漫
          </span>
          <span class="tag-item" @click="handleTagClick('游戏')">
            游戏
          </span>
          <span class="tag-item" @click="handleTagClick('动物')">
            动物
          </span>
          <span class="tag-item" @click="handleTagClick('美女壁纸')">
            美女壁纸
          </span>
          <span class="tag-item" @click="handleTagClick('城市')">
            城市
          </span>
          <span class="tag-item" @click="handleTagClick('森林')">
            森林
          </span>
          <span class="tag-item" @click="handleTagClick('雪山')">
            雪山
          </span>
          <span class="tag-item" @click="handleTagClick('沙漠')">
            沙漠
          </span>
          <span class="tag-item" @click="handleTagClick('花海')">
            花海
          </span>
          <span class="tag-item" @click="handleTagClick('瀑布')">
            瀑布
          </span>
          <span class="tag-item" @click="handleTagClick('日落')">
            日落
          </span>
          <span class="tag-item" @click="handleTagClick('极光')">
            极光
          </span>
          <span class="tag-item" @click="handleTagClick('古风')">
            古风
          </span>
          <span class="tag-item" @click="handleTagClick('科幻')">
            科幻
          </span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getSelectedWallpapers } from '@/api'

const router = useRouter()

// 全局缓存管理
const globalCache = new Map()
const preloadQueue = ref([])
const isPreloading = ref(false)

// 精选壁纸数据
const selectedWallpapers = ref([])
const loading = ref(false)
const failedImages = ref(new Set()) // 记录加载失败的图片ID

// 获取精选壁纸数据
const fetchSelectedWallpapers = async () => {
  loading.value = true
  try {
    const response = await getSelectedWallpapers()
    if (response.code === 200) {
      selectedWallpapers.value = response.data || []
      
      // 预加载所有文件
      selectedWallpapers.value.forEach(image => {
        if (image.url) {
          addToPreloadQueue(image.url)
        }
      })
    } else {
      console.error('获取精选壁纸失败:', response.msg)
    }
  } catch (error) {
    console.error('获取精选壁纸失败:', error)
  } finally {
    loading.value = false
  }
}

// 预加载文件
const preloadFile = async (url) => {
  if (getCachedBlob(url)) return // 已缓存
  
  try {
    const response = await fetch(url, {
      method: 'GET',
      mode: 'cors',
      credentials: 'omit',
      headers: {
        'Accept': isVideo(url) ? 'video/*' : 'image/*',
        'Cache-Control': 'max-age=600' // 10分钟缓存
      }
    })
    
    if (response.ok) {
      const blob = await response.blob()
      setCachedBlob(url, blob)
    }
  } catch (error) {
    // 预加载失败，静默处理
  }
}

// 处理图片加载失败
const handleImageError = (imageId) => {
  failedImages.value.add(imageId)
}



// 打开图片详情页面（已禁用）
// const openImageModal = (image) => {
//   // 检查是否有缓存
//   const cachedBlob = getCachedBlob(image.url)
//   const hasCache = !!cachedBlob
//   
//   // 在新标签页中打开详情页面，传递图片信息和缓存状态
//   const url = `/wallpaper/${image.id}?url=${encodeURIComponent(image.url)}&title=${encodeURIComponent(image.name)}&description=${encodeURIComponent(`这是一张精美的${image.name}壁纸，展现了独特的艺术魅力。`)}&resolution=${encodeURIComponent('4K')}&downloads=${image.download || 0}&likes=${Math.floor(Math.random() * 200) + 50}&classify=${encodeURIComponent(image.classify || '精选壁纸')}&tags=${encodeURIComponent(image.classify || '精选壁纸,4K')}&cached=${hasCache}`
//   window.open(url, '_blank')
// }

// 视频加载错误处理
const handleVideoError = (event) => {
  console.error('视频加载失败:', event)
}

// 视频加载成功处理
const handleVideoLoad = () => {
  // 视频加载成功
}

// 判断是否为视频格式
const isVideo = (url) => {
  return url.toLowerCase().endsWith('.mp4') || url.toLowerCase().endsWith('.mov') || url.toLowerCase().endsWith('.webm')
}

// 缓存管理函数
const getCachedBlob = (url) => {
  const cached = globalCache.get(url)
  if (cached && Date.now() - cached.timestamp < 600000) { // 10分钟缓存
    return cached.blob
  }
  // 清理过期缓存
  if (cached) {
    globalCache.delete(url)
  }
  return null
}

const setCachedBlob = (url, blob) => {
  // 清理旧缓存，保持缓存大小在合理范围内
  if (globalCache.size > 50) {
    const oldestKey = globalCache.keys().next().value
    globalCache.delete(oldestKey)
  }
  
  globalCache.set(url, {
    blob,
    timestamp: Date.now()
  })
}

// 预加载队列处理
const processPreloadQueue = async () => {
  if (isPreloading.value || preloadQueue.value.length === 0) return
  
  isPreloading.value = true
  const url = preloadQueue.value.shift()
  
  try {
    await preloadFile(url)
  } finally {
    isPreloading.value = false
    // 继续处理队列
    if (preloadQueue.value.length > 0) {
      setTimeout(processPreloadQueue, 50) // 减少延迟
    }
  }
}

// 添加预加载任务
const addToPreloadQueue = (url) => {
  if (!preloadQueue.value.includes(url) && !getCachedBlob(url)) {
    preloadQueue.value.push(url)
    processPreloadQueue()
  }
}

// 处理标签点击
const handleTagClick = (tagName) => {
  // 可以跳转到搜索页面或分类页面
  router.push({
    name: 'Search',
    query: {q: tagName}
  })
}



// 组件挂载时获取数据
onMounted(() => {
  // 将全局缓存暴露到window对象，供其他页面使用
  window.globalCache = globalCache
  
  fetchSelectedWallpapers()
})
</script>

<style scoped lang="less">
.app-content-illustrate {
  height: 250px; /* 减少高度 */
  position: relative; /* 添加相对定位 */
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  overflow: hidden; /* 确保视频不会溢出容器 */

  .video-background {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;
    z-index: 0; /* 调整z-index */

    .background-video {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      object-fit: cover; /* 确保视频覆盖整个容器 */
      z-index: 0; /* 调整z-index */
      min-width: 100%;
      min-height: 100%;
    }

    .fallback-background {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-image: url("https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=1200&h=400&fit=crop");
      background-size: cover;
      background-position: center;
      background-repeat: no-repeat;
      z-index: -1; /* 在视频后面作为备用 */
      opacity: 0.8;
    }
  }

  .content-overlay {
    background: rgba(0, 0, 0, 0.3);
    backdrop-filter: blur(2px);
    padding: 20px;
    border-radius: 10px;
    text-align: center;
    z-index: 10; /* 确保在视频之上 */
    position: relative; /* 添加相对定位 */

    p {
      color: white;
      text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
      font-size: 18px;
      line-height: 1.8;
    }
  }
}

.app-content-dynamic-images {
  padding: 30px 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 12px;
  margin: 0 30px 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);

  /* 加载状态 */
  .loading {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 60px 0;
    color: #666;
  }

  .loading-spinner {
    width: 40px;
    height: 40px;
    border: 4px solid #f3f3f3;
    border-top: 4px solid #3b82f6;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 16px;
  }

  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }

  /*精选壁纸*/
  .section-title {
    font-size: 28px;
    font-weight: 600;
    margin-bottom: 40px;
    text-align: center;
    color: #2c3e50;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;

    &::after {
      content: '';
      position: absolute;
      bottom: -8px;
      left: 50%;
      transform: translateX(-50%);
      width: 60px;
      height: 3px;
      background: linear-gradient(90deg, #3498db, #2ecc71);
      border-radius: 2px;
    }
  }

  .image-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20px;
    max-width: 1250px;
    margin: 0 auto;
  }

  .image-card {
    width: 100%;
    aspect-ratio: 4/3;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    position: relative;

    &:hover {
      transform: translateY(-8px) scale(1.02);
      box-shadow: 0 15px 35px rgba(0, 0, 0, 0.25);
    }

    .image-wrapper {
      position: relative;
      width: 100%;
      height: 100%;
      overflow: hidden;

      .grid-image,
      .grid-video {
        width: 100%;
        height: 100%;
        object-fit: cover;
        transition: transform 0.3s ease;
      }

      .grid-video {
        width: 100%;
        height: 100%;
        object-fit: cover;
        transition: transform 0.3s ease;
        pointer-events: none; /* 禁用视频的点击事件 */
      }

      .image-overlay {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: linear-gradient(135deg, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0.4) 100%);
        display: flex;
        justify-content: center;
        align-items: center;
        opacity: 0;
        transition: all 0.3s ease;
        color: white;
        text-align: center;
        padding: 20px;
      }

      &:hover {
        .image-overlay {
          opacity: 1;
        }

        .grid-image,
        .grid-video {
          transform: scale(1.1);
        }
      }
    }

    .overlay-content {
      h4 {
        font-size: 20px;
        margin-bottom: 8px;
        font-weight: 600;
        text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
      }

      p {
        font-size: 14px;
        color: #e8e8e8;
        line-height: 1.4;
        text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
      }
    }
  }
}

/*热门标签*/
.app-content-Hot-Tags {
  padding: 20px 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 12px;
  margin: 0 30px 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);

  .hot-tags-header {
    font-size: 28px;
    font-weight: 600;
    margin-bottom: 40px;
    text-align: center;
    color: #2c3e50;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;

    .section-title {
      font-size: 28px;
      font-weight: 600;
      text-align: center;
      color: #2c3e50;
      position: relative;
      display: flex;
      align-items: center;
      justify-content: center;

      &::after {
        content: '';
        position: absolute;
        bottom: -8px;
        left: 50%;
        transform: translateX(-50%);
        width: 60px;
        height: 3px;
        background: linear-gradient(90deg, #3498db, #2ecc71);
        border-radius: 2px;
      }
    }
  }

  /*标签的具体内容*/
  .app-content-Hot-Tags-box{
    height: 200px;
    margin: 5px 60px;
    border: 2px dashed #ccc;
  }

  // 标签网格样式
  .tags-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
    gap: 12px;
    padding: 20px;
    height: 100%;
    overflow-y: auto;

    .tag-item {
      display: flex;
      align-items: center;
      gap: 6px;
      background: rgba(255, 255, 255, 0.15);
      color: #2c3e50;
      padding: 10px 12px;
      border-radius: 8px;
      font-size: 13px;
      font-weight: 500;
      cursor: pointer;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      border: 1px solid rgba(255, 255, 255, 0.2);
      backdrop-filter: blur(5px);
      position: relative;
      overflow: hidden;
      text-align: center;
      justify-content: center;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

      &::before {
        content: '';
        position: absolute;
        top: 0;
        left: -100%;
        width: 100%;
        height: 100%;
        background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
        transition: left 0.5s ease;
      }

      &:hover {
        background: rgba(255, 255, 255, 0.3);
        transform: translateY(-2px) scale(1.02);
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
        border-color: rgba(255, 255, 255, 0.4);
        color: #1a202c;

        &::before {
          left: 100%;
        }
      }

      &:active {
        transform: translateY(0) scale(0.98);
      }
    }

    @media (max-width: 768px) {
      grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
      gap: 10px;
      padding: 15px;

      .tag-item {
        padding: 8px 10px;
        font-size: 12px;
      }
    }
  }
}
</style> 